package com.jmxcfc.blfsc.langyu.util;

import com.jmxcfc.blfsc.common.common.ComConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Map;
import java.util.Objects;

/**
 * http请求工具类
 */
@Slf4j
@Component
public class HttpClientUtil {

    private RestTemplate restTemplate;

    @Autowired
    public void setRestTemplate(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    /**
     * 自定义请求头和请求体的POST请求调用方式
     *
     * @param url          请求URL
     * @param headers      请求头参数
     * @param responseType 返回对象类型
     * @return ResponseEntity 响应对象封装类
     */
    public <T> ResponseEntity<T> post(String url, String body, Map<String, String> headers, Class<T> responseType) {
        return exchange(url, HttpMethod.POST, body, headers, responseType);
    }

    /**
     * 通用调用方式
     *
     * @param url          请求URL
     * @param method       请求方法类型
     * @param body         JSONObject.toStrig()
     * @param headers      请求头参数
     * @param responseType 返回对象类型
     * @return ResponseEntity 响应对象封装类
     */
    private <T> ResponseEntity<T> exchange(String url, HttpMethod method, String body, Map<String, String> headers, Class<T> responseType) {
        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.setContentType(MediaType.parseMediaType(ComConstants.MEDIA_TYPE));
        requestHeaders.setAll(headers);
        //设置访问的Entity
        HttpEntity<String> requestEntity = new HttpEntity<>(body,requestHeaders);
        return restTemplate.exchange(url, method, requestEntity, responseType);
    }

    /**
     * 获取响应报文
     */
    public String responseDataToString(ResponseEntity<String> responseEntity) throws Exception {
        log.info("接口响应报文responseEntity:{}",responseEntity);
        int statusCodeValue = responseEntity.getStatusCodeValue();
        if (Objects.equals(statusCodeValue,HttpStatus.OK.value())) {
            log.info("接口响应body:{}",responseEntity.getBody());
            return responseEntity.getBody();
        } else {
            log.error("接口响应body响应状态不正确,responseEntity:{}",responseEntity);
            throw new Exception("接口响应body响应状态不正确");
        }
    }
}

